package util

import (
	"crypto/md5"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"math/rand"
	"mime/multipart"
	"os"
	"strings"
	"time"
)

func Md5(str string) string {
	d := []byte(str)
	return fmt.Sprintf("%x", md5.Sum(d))
}

func CreateDir(folderPath string) string {
	if _, err := os.Stat(folderPath); os.IsNotExist(err) {
		_ = os.MkdirAll(folderPath, os.ModePerm)
	}
	return folderPath
}

func Md5Sign(key string, field... string) string {
	return Md5(key + ":" + strings.Join(field, "-"))
}

func VerifyMd5Sign(sign string, key string, field ...string) bool {
	return Md5(key + ":" + strings.Join(field, "-")) == sign
}

func SaveSession(c *gin.Context, key string, value interface{}) bool {
	session := sessions.Default(c)
	session.Set(key, value)
	if err := session.Save(); err != nil {
		return false
	}
	return true
}

func GetSession(c *gin.Context, key string) interface{} {
	session := sessions.Default(c)
	return session.Get(key)
}

func RemoveSession(c *gin.Context, key string) {
	session := sessions.Default(c)
	session.Delete(key)
	_ = session.Save()
}

func RandString(len int) string {
	r := rand.New(rand.NewSource(time.Now().Unix()))
	bytes := make([]byte, len)
	for i := 0; i < len; i++ {
		b := r.Intn(26) + 65
		bytes[i] = byte(b)
	}
	return string(bytes)
}

func GenSmsCode(width int) string {
	numeric := [10]byte{0,1,2,3,4,5,6,7,8,9}
	r := len(numeric)
	rand.Seed(time.Now().UnixNano())

	var sb strings.Builder
	for i := 0; i < width; i++ {
		_, _ = fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
	}
	return sb.String()
}

func GetImage(src string) string {
	prefix := GetSettingValue("image_domain")
	return prefix + src
}

func GetImgExt(file *multipart.FileHeader) (ext string, err error) {
	var headerByte []byte
	file.Header.Get("")
	headerByte = make([]byte, 8)
	fd, err := file.Open()
	if err != nil {
		return "", err
	}

	defer fd.Close()
	_, err = fd.Read(headerByte)
	if err != nil {
		return "", err
	}
	xStr := fmt.Sprintf("%x", headerByte)
	switch {
	case xStr == "89504e470d0a1a0a":
		ext = ".png"
	case xStr == "0000010001002020":
		ext = ".ico"
	case xStr == "0000020001002020":
		ext = ".cur"
	case xStr[:12] == "474946383961" || xStr[:12] == "474946383761":
		ext = ".gif"
	case xStr[:10] == "0000020000" || xStr[:10] == "0000100000":
		ext = ".tga"
	case xStr[:8] == "464f524d":
		ext = ".iff"
	case xStr[:8] == "52494646":
		ext = ".ani"
	case xStr[:4] == "4d4d" || xStr[:4] == "4949":
		ext = ".tiff"
	case xStr[:4] == "424d":
		ext = ".bmp"
	case xStr[:4] == "ffd8":
		ext = ".jpg"
	case xStr[:2] == "0a":
		ext = ".pcx"
	default:
		ext = ""
	}
	return ext, nil
}
